package br.usp.poli.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;

public class ImportDaemon implements Runnable {

	static {
		ItsInitializer.initialize();
	}


	public void run() {
		while (true) {
			System.out.println("ImportDaemon scanning files...");
			String sourceDirectory = "data/queue";
			String destinyDirecotory = "data/imported";
			File dir = new File(sourceDirectory);
			File[] files = dir.listFiles();
			if (files == null) {
				System.out.println(sourceDirectory
						+ " does not denote a directory");
			} else {
				importFiles(destinyDirecotory, files);
			}
			try {
				Thread.sleep(5 * 60 * 1000);
			} catch (InterruptedException e) {
			}
		}
	}

	private void importFiles(String destinyDirecotory, File[] files) {
		for (File file : files) {
			String name = file.getName();
			String[] nameFields = name.split("-");
			if (nameFields.length == 3) {
				String instrument = nameFields[0];
				String instrumentSerial = nameFields[1];
				int dot = nameFields[2].lastIndexOf(".");
			//	String counter = nameFields[2].substring(0, dot);
				String extension = nameFields[2].substring(dot);
				if (accept(extension)) {
					try {
						InputStream inputStream = new FileInputStream(file);
						if (("hobo".equalsIgnoreCase(instrument))) {
							HoboImport.fillOccurrences(inputStream,
									instrumentSerial);
							file.renameTo(new File(destinyDirecotory + "/"
									+ name));
						}
						if (("WheatherStation".equalsIgnoreCase(instrument))) {
							WheatherStationImport.fillOccurrences(inputStream,
									instrumentSerial);
							file.renameTo(new File(destinyDirecotory + "/"
									+ name));
						}
						if (("xarope".equalsIgnoreCase(instrument))) {
							XaropeImport.fillOccurrences(inputStream,
									instrumentSerial);
							file.renameTo(new File(destinyDirecotory + "/"
									+ name));
						}
						System.out.println("Imported " + file.toString());
					} catch (FileNotFoundException e) {
						throw new IllegalStateException();
					}
				}
			}
		}
	}

	private boolean accept(String extension) {
		return (".csv".equalsIgnoreCase(extension))
				|| (".txt".equalsIgnoreCase(extension));
	}

}
